package cn.josh.daolmpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.josh.bean.Ec_article;
import cn.josh.dao.Ec_articleDao;
import cn.josh.utill.JDBCUtil;

public class Ec_articleDaoImpl implements Ec_articleDao 
{

	@Override
	public List<Ec_article> findAll(String type_code ,String search ,String selectType) 
	{
		String sql = "";
		//如果传入参数都为空，查询所有数据
		//如果其一不为空，则按类型查询数据
		if(type_code == null && search == null && selectType == null)
		{
			sql = "select * from ec_article";
		}
		else if(type_code != null)
		{
			sql = "select * from ec_article where type_code like '" + type_code + "%';";
		}
		else if(search != null)
		{
			//根据单选列表查询数据
			if(selectType == null)
			{
				sql = "SELECT * FROM ec_article WHERE CONCAT(title,supplier,price,locality,description) LIKE '%" + search + "%';";
			}
			else
			{
				sql = "SELECT * FROM ec_article WHERE type_code like '" + selectType + "%' AND CONCAT(title,supplier,price,locality,description) LIKE '%" + search + "%';";
			}
			
		}
		
		ResultSet rs = JDBCUtil.executeQuery(sql,null);
		
		List<Ec_article> goods = new ArrayList<Ec_article>();
		
		try
		{
			while(rs.next())
			{
				Ec_article ec_ar = new Ec_article();
				ec_ar.setId(rs.getString("ID"));
				ec_ar.setTypeCode(rs.getString("TYPE_CODE"));
				ec_ar.setTitle(rs.getString("TITLE"));
				ec_ar.setSupplier(rs.getString("SUPPLIER"));
				ec_ar.setPrice(rs.getString("PRICE"));
				ec_ar.setDiscount(rs.getString("DISCOUNT"));
				ec_ar.setLocality(rs.getString("LOCALITY"));
				ec_ar.setStorage(rs.getString("STORAGE"));
				ec_ar.setImage(rs.getString("IMAGE"));
				ec_ar.setDescription(rs.getString("DESCRIPTION"));
			
				goods.add(ec_ar);
				
			} 
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		//新特性 输出容器
		goods.forEach(li->System.out.println(li));

		
		return goods;
	}

	@Override
	public Ec_article findById(String id) 
	{
		String sql = "SELECT * FROM ec_article WHERE id = ?;";
		String[] info = {id};
		ResultSet rs = JDBCUtil.executeQuery(sql, info);
		
		try 
		{
			if(rs.next())
			{
				Ec_article ec_ar = new Ec_article();
				ec_ar.setId(rs.getString("ID"));
				ec_ar.setTypeCode(rs.getString("TYPE_CODE"));
				ec_ar.setTitle(rs.getString("TITLE"));
				ec_ar.setSupplier(rs.getString("SUPPLIER"));
				ec_ar.setPrice(rs.getString("PRICE"));
				ec_ar.setDiscount(rs.getString("DISCOUNT"));
				ec_ar.setLocality(rs.getString("LOCALITY"));
				ec_ar.setStorage(rs.getString("STORAGE"));
				ec_ar.setImage(rs.getString("IMAGE"));
				ec_ar.setDescription(rs.getString("DESCRIPTION"));
				
				return ec_ar;
			}
			
			
		} 
		catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

}
